﻿using System.IO;
using System.Text;
using System.Windows;

namespace WpfSample
{
    /// <summary>
    /// BrowserView.xaml 的交互逻辑
    /// </summary>
    // ReSharper disable once RedundantExtendsListEntry
    public partial class BrowserView : System.Windows.Controls.UserControl
    {
        public BrowserView()
        {
            InitializeComponent();

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog()
            {
                Filter = @"Markdown files (*.md)|*.md|All files (*.*)|*.*" //选择的文件类型的筛选器
            };
            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            TextBoxFilePath.Text = openFileDialog.FileName;
            
            var content = File.ReadAllText(openFileDialog.FileName);
            var html = Markdig.Markdown.ToHtml(content);
            WebBrowser.NavigateToString(ConvertExtendedAscii(html));
        }

        private static string ConvertExtendedAscii(string html)
        {
            var retVal = "";
            var s = html.ToCharArray();

            foreach (var c in s)
            {
                if (Convert.ToInt32(c) > 127)
                    retVal += "&#" + Convert.ToInt32(c) + ";";
                else
                    retVal += c;
            }

            return retVal;
        }
    }
}
